package com.example.mymvvmdemo;

import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.webkit.WebView;
import androidx.core.content.ContextCompat;
import com.example.mymvvmdemo.constants.Constants;
import com.example.mymvvmdemo.utils.LogUtils;
import com.example.mymvvmdemo.utils.SpUtils;
import com.example.mymvvmdemo.utils.StrUtils;


public class MyApplication extends Application {

    private static MyApplication myApplication = null;
    private static String AUTH_TOKEN = "";
    private static Context context;

    public static MyApplication getInstance() {
        return myApplication;
    }

    /**
     * 获取全局token
     *
     * @return AppToken
     */
    public static String getAuthToken() {
        String token = SpUtils.getSpUtils(MyApplication.getInstance(), Constants.ACCOUNT_NAME)
                .getStringValue(Constants.SP_AUTH_TOKEN, "");
        if (StrUtils.isEmpty(AUTH_TOKEN)) {
            AUTH_TOKEN = token;
            LogUtils.d("获取token:" + token);
        }
//        LogUtils.d("当前使用的token: " + AUTH_TOKEN);
        return AUTH_TOKEN;
    }

    public static void setAuthToken(String authToken) {
        AUTH_TOKEN = authToken;
        SpUtils.getSpUtils(MyApplication.getInstance(), Constants.ACCOUNT_NAME)
                .putValue(Constants.SP_AUTH_TOKEN, authToken);
        LogUtils.d("设置新token: " + authToken);
    }

    public static Context getContext() {
        return context;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        myApplication = this;
        context = this;

        boolean isPrivate = SpUtils.getSpUtils(this, Constants.ACCOUNT_NAME)
                .getBooleanValue(Constants.USER_PRIVATE, false);
        //判断用户是否同意隐私协议
        if (!isPrivate) {
            return;
        }
        LogUtils.setIsPrivate(true);
        String storageRootPath = "";
        if (Build.VERSION.SDK_INT < 29) {
            storageRootPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        } else {
            storageRootPath = ContextCompat.getExternalFilesDirs(
                    MyApplication.getInstance().getApplicationContext(), null)[0].getAbsolutePath();
        }
        Constants.FILE_PREFIX = storageRootPath + Constants.FILES_APP;
        initSdk();
        initWebView();
    }

    private void initWebView() {
        try {
            new WebView(this).destroy();
        } catch (Exception e) {
        }
    }

    public void initSdk() {

        //保存日志到 /storage/emulated/0/Sunba/push_log.txt
        LogUtils.init(this);
        LogUtils.setFileLog(true);
        String logPath = LogUtils.getLogPath();
        LogUtils.d("日志路径：" + logPath);


    }

}
